<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <!-- 市县改为下拉框 -->
            <el-form-item label="区域" prop="region">
              <el-select v-model="queryParams.region" placeholder="请输入区域">
                <el-option v-for="city in cityOptions" :key="city.id" :label="city.name" :value="city.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="险种" prop="insuranceType">
              <el-select v-model="queryParams.insuranceType" placeholder="请选择险种" clearable >
                <el-option
                  v-for="category in CategoryOptions"
                  :key="category.categoryName"
                  :label="category.categoryName"
                  :value="category.categoryName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" style="width: 350px">
              <el-date-picker
                v-model="dateRangeCreateTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </el-form-item>
            <el-form-item label="">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['Nyt7Claim:Nyt7Claim:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button v-hasPermi="['Nyt7Claim:Nyt7Claim:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <div class="dashboard-container">
        <el-row :gutter="10" class="mt-5">
          <el-col :xs="24" :span="24" style="margin-right: 15px">
            <Chart3_claim
              :chart-data="chartData"
              width="100%"
              height="400px"
              :post-options="postOptions"
              :city-options="cityOptions"
              :refresh-chart-data="getList"
              :CategoryOptions="CategoryOptions"
            />
          </el-col>
        </el-row>
      </div>
    </el-card>
    <!-- 添加或修改保险理赔对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" append-to-body>
      <el-form ref="Nyt7ClaimFormRef" :model="form" :rules="rules" label-width="110px">
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span class="title">理赔信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
        <el-form-item label="保险公司名称" prop="companyName">
          <el-select v-model="form.companyName" placeholder="请输入保险公司名称">
            <el-option v-for="postName in postOptions" :key="postName.postName" :label="postName.postName" :value="postName.postName" />
          </el-select>
        </el-form-item>
            </el-col>
            <el-col :span="12">
        <!-- 市县改为下拉框 -->
        <el-form-item label="区域" prop="region">
          <el-select v-model="form.region" placeholder="请输入区域">
            <el-option v-for="city in cityOptions" :key="city.id" :label="city.name" :value="city.name" />
          </el-select>
        </el-form-item>
            </el-col>
            <el-col :span="12">
        <el-form-item label="险种" prop="insuranceType">
          <el-select v-model="form.insuranceType" placeholder="请选择险种">
            <el-option v-for="category in CategoryOptions" :key="category.categoryName" :label="category.categoryName" :value="category.categoryName" />
          </el-select>
        </el-form-item>
            </el-col>
            <el-col :span="12">
        <el-form-item label="已决赔款面积" prop="claimArea">
          <el-input v-model="form.claimArea" placeholder="请输入已决赔款面积" />
        </el-form-item>
            </el-col>
            <el-col :span="12">
        <el-form-item label="已决赔款户数" prop="claimHouseholds">
          <el-input v-model="form.claimHouseholds" placeholder="请输入已决赔款户数" />
        </el-form-item>
            </el-col>
            <el-col :span="12">
        <el-form-item label="已决赔款总额" prop="claimAmount">
          <el-input v-model="form.claimAmount" placeholder="请输入已决赔款总额" />
        </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Nyt7Claim" lang="ts">
import { listNyt7Claim, getNyt7Claim, delNyt7Claim, addNyt7Claim, updateNyt7Claim, Nyt7ClaimChart } from '@/api/Nyt7Claim/Nyt7Claim';
import { Nyt7ClaimVO, Nyt7ClaimQuery, Nyt7ClaimForm } from '@/api/Nyt7Claim/Nyt7Claim/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const Nyt7ClaimList = ref<Nyt7ClaimVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const Nyt7ClaimFormRef = ref<ElFormInstance>();

// 定义 chartData 用于传递给 Chart3_claim
const chartData = ref<Nyt7ClaimVO[] | null>(null);

//引入区域管理的API和类型
import { listNyt7RegionManagement } from '@/api/Nyt7RegionManagement/Nyt7RegionManagement';
import { Nyt7RegionManagementVO } from '@/api/Nyt7RegionManagement/Nyt7RegionManagement/types';
import { PostVO } from '@/api/system/post/types';
import { listPost } from '@/api/system/post';
import Chart3_claim from '@/views/Nyt7Claim/claim_chart/Chart3_claim.vue';
import { Nyt7InsuranceCategoryVO } from '@/api/Nyt7InsuranceCategory/Nyt7InsuranceCategory/types';
import { listNyt7InsuranceCategory } from '@/api/Nyt7InsuranceCategory/Nyt7InsuranceCategory';

//dinghies区域管理数据和选项
const regionManagementList = ref<Nyt7RegionManagementVO[]>([]);
const cityOptions = ref<Nyt7RegionManagementVO[]>([]);
const countyOptions = ref<Nyt7RegionManagementVO[]>([]);
const CategoryOptions = ref<Nyt7InsuranceCategoryVO[]>([]);
const CategoryList = ref<Nyt7InsuranceCategoryVO[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: Nyt7ClaimForm = {
  id: undefined,
  companyName: undefined,
  region: undefined,
  insuranceType: undefined,
  claimArea: undefined,
  claimHouseholds: undefined,
  claimAmount: undefined
};
const data = reactive<PageData<Nyt7ClaimForm, Nyt7ClaimQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    companyName: undefined,
    region: undefined,
    insuranceType: undefined,
    claimArea: undefined,
    claimHouseholds: undefined,
    claimAmount: undefined,
    params: {
      createTime: undefined
    }
  },
  rules: {
    id: [{ required: true, message: '理赔ID不能为空', trigger: 'blur' }],
    companyName: [{ required: true, message: '保险公司名称不能为空', trigger: 'blur' }],
    region: [{ required: true, message: '区域不能为空', trigger: 'blur' }],
    insuranceType: [{ required: true, message: '险种不能为空', trigger: 'change' }],
    claimArea: [{ required: true, message: '已决赔款面积不能为空', trigger: 'blur' }],
    claimHouseholds: [{ required: true, message: '已决赔款户数不能为空', trigger: 'blur' }],
    claimAmount: [{ required: true, message: '已决赔款总额不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询保险理赔列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  const res = await Nyt7ClaimChart(queryParams.value);
  total.value = res.total;
  chartData.value = res.data;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  Nyt7ClaimFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  reset();
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: Nyt7ClaimVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加保险理赔';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: Nyt7ClaimVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getNyt7Claim(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改保险理赔';
};

/** 提交按钮 */
const submitForm = () => {
  Nyt7ClaimFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateNyt7Claim(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addNyt7Claim(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: Nyt7ClaimVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除保险理赔编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delNyt7Claim(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'Nyt7Claim/Nyt7Claim/export',
    {
      ...queryParams.value
    },
    `Nyt7Claim_${new Date().getTime()}.xlsx`
  );
};

//获取区域管理数据的方法
const getRegionManagementList = async () => {
  const res = await listNyt7RegionManagement();
  regionManagementList.value = res.data;
  console.log(regionManagementList);
  cityOptions.value = regionManagementList.value.filter((item) => item.pid == '182754'); // 假设parentId为0的是市
};

//处理市的选择变化
const handleCityChange = (cityName: string) => {
  const selectedCity = cityOptions.value.find((city) => city.name === cityName);
  if (selectedCity) {
    countyOptions.value = regionManagementList.value.filter((item) => item.pid === selectedCity.id);
  } else {
    countyOptions.value = [];
  }
};

const postList = ref<PostVO[]>([]);
const postOptions = ref<PostVO[]>([]);

//获取保险公司数据
const getPostList = async () => {
  const res = await listPost();
  postList.value = res.rows;
  postOptions.value = postList.value;
  console.log(res);
  console.log(postList);
};

//获取保险产品类型数据
const getCategoryList = async () => {
  const res = await listNyt7InsuranceCategory();
  CategoryList.value = res.data;
  console.log('category,res');
  console.log(CategoryList);
  CategoryOptions.value = CategoryList.value.filter(item => item.parentId == '0');
  console.log('category,res');
  console.log(res);
  console.log(CategoryOptions.value);
};

onMounted(() => {
  getList();
  getRegionManagementList();
  getPostList();
  getCategoryList();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 24px;
}
</style>
